package com.zds.zhouyi;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;
import com.zds.zhouyi.model.Const;
import com.zds.zhouyi.model.Gua;
import com.zds.zhouyi.model.History;
import com.zds.zhouyi.ui.CustomDialog;
import com.zds.zhouyi.ui.HistoryDialog;
import com.zds.zhouyi.ui.LoadingDialog;
import com.zds.zhouyi.ui.NormalDialog;
import com.zds.zhouyi.ui.QuickGuaAdapter;
import com.zds.zhouyi.ui.QuickHistoryAdapter;
import com.zds.zhouyi.util.ResUtil;
import com.zds.zhouyi.util.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;

/**
 * @author ZDS
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    TextView tvStart;
    TextView tvStartTips;
    ConstraintLayout coinLayout;
    TextView coin1;
    TextView coin2;
    TextView coin3;
    TextView tvResult;

    TextView tvSeeAll;
    TextView tvSeeHistory;
    RecyclerView rvAll;
    RecyclerView rvHistory;
    Gua nowGua = null;
    QuickHistoryAdapter quickHistoryAdapter;
    /**
     * -1 初始状态 ：文案：开始预测 -->
     * <p>
     * 0 投第一次 出第一次 铜钱：文案：请再投一次 -->
     * 1 投第二次 出结果：文案：再算一卦
     */
    int clickCount = -1;

    int[] result1;
    int[] result2;

    LinearLayout llGua;
    ImageView gua1;
    ImageView gua2;
    ImageView gua3;
    ImageView gua4;
    ImageView gua5;
    ImageView gua6;
    CustomDialog.Builder builder;
    NormalDialog.Builder normalBuilder;

    ArrayList<Gua> dataList;
    LoadingDialog loadingDialog;
    HistoryDialog historyDialog;
    MMKV mmkv;
    Gson gson;
    ArrayList<History> allHistory = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取 MMKV 实例
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();
        dataList = readJsonFromAssets();
        result1 = new int[3];
        result2 = new int[3];
        tvStart = findViewById(R.id.tv_start);
        tvStartTips = findViewById(R.id.tv_start_tips);
        //初始化 loading 弹窗
        loadingDialog = new LoadingDialog(this);

        tvResult = findViewById(R.id.tv_result);
        coinLayout = findViewById(R.id.cl_coin_result);
        coin1 = findViewById(R.id.iv_coin1);
        coin2 = findViewById(R.id.iv_coin2);
        coin3 = findViewById(R.id.iv_coin3);
        tvSeeAll = findViewById(R.id.tv_see_all);
        tvSeeHistory = findViewById(R.id.tv_see_history);
        llGua = findViewById(R.id.ll_gua_result);
        gua1 = findViewById(R.id.iv_gua1);
        gua2 = findViewById(R.id.iv_gua2);
        gua3 = findViewById(R.id.iv_gua3);
        gua4 = findViewById(R.id.iv_gua4);
        gua5 = findViewById(R.id.iv_gua5);
        gua6 = findViewById(R.id.iv_gua6);
        //查看所有卦
        rvAll = findViewById(R.id.rv_all);
        rvAll.setLayoutManager(new LinearLayoutManager(this));
        QuickGuaAdapter guaAdapter = new QuickGuaAdapter(dataList);
        rvAll.setAdapter(guaAdapter);
        guaAdapter.setOnItemClickListener((adapter, view, position) -> {
            //弹窗 查看详情
            if (builder == null) {
                builder = new CustomDialog.Builder(view.getContext());
            }
            Gua gua = dataList.get(position);
            builder.setContent(gua.toString()).create().show();
        });

        //查看历史记录
        initHistoryList();

        tvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickCount++;
                loadingDialog.showLoading();
                v.postDelayed(() -> {
                    // 隐藏 loading 弹窗
                    if (loadingDialog.isShowing()) {
                        loadingDialog.hideLoading();
                    }

                    if (clickCount == 0) {
                        tvStart.setText(R.string.try_again);
                        llGua.setVisibility(View.INVISIBLE);
                        tvResult.setVisibility(View.INVISIBLE);
                        coinLayout.setVisibility(View.INVISIBLE);
                    }

                    getCoinResult();
                    Log.d(TAG, "onClick clickCount=" + clickCount);
                    if (clickCount > 1) {
                        clickCount = 0;
                        tvStart.setText(R.string.try_again);
                        llGua.setVisibility(View.INVISIBLE);
                        tvResult.setVisibility(View.INVISIBLE);
                    }

                }, 1000);

            }
        });
        llGua.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗 查看详情
                if (builder == null) {
                    builder = new CustomDialog.Builder(v.getContext());
                }
                if (nowGua != null) {
                    builder.setContent(nowGua.toString()).create().show();
                }
            }
        });

        tvResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗 查看详情
                if (builder == null) {
                    builder = new CustomDialog.Builder(v.getContext());
                }
                if (nowGua != null) {
                    builder.setContent(nowGua.toString()).create().show();
                }
            }
        });

        String seeAllStr = getResources().getString(R.string.see_all);
        String foldingStr = getResources().getString(R.string.folding);
        tvSeeAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rvHistory.getVisibility() == View.VISIBLE) {
                    rvHistory.setVisibility(View.GONE);
                }
                if (Objects.equals(tvSeeAll.getText().toString(), seeAllStr)) {
                    tvSeeAll.setText(foldingStr);
                    rvAll.setVisibility(View.VISIBLE);
                } else {
                    tvSeeAll.setText(seeAllStr);
                    rvAll.setVisibility(View.GONE);
                }
            }
        });

        tvSeeHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvHistory.setVisibility(rvHistory.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                tvSeeHistory.setText(rvHistory.getVisibility() == View.VISIBLE ? R.string.hide_history : R.string.see_history);
            }
        });

    }

    private void initHistoryList() {
        try {
            Type historyListType = new TypeToken<List<History>>() {
            }.getType();
            ArrayList<History> list = gson.fromJson(mmkv.decodeString(Const.HISTORY_KEY), historyListType);
            if (list != null) {
                allHistory.addAll(list);
            }
        } catch (Exception e) {
            Log.e(TAG, "gson e=" + e);
        }
        rvHistory = findViewById(R.id.rv_history);
        rvHistory.setLayoutManager(new LinearLayoutManager(this));
        rvHistory.setItemAnimator(null);
        quickHistoryAdapter = new QuickHistoryAdapter();
        rvHistory.setAdapter(quickHistoryAdapter);
        allHistory.sort(new Comparator<History>() {
            @Override
            public int compare(History item1, History item2) {
                return Long.compare(item2.getTime(), item1.getTime());
            }
        });

        quickHistoryAdapter.setList(allHistory);
        quickHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ArrayList<History> list = (ArrayList<History>) adapter.getData();
                if (list.size() == 1) {
                    list.get(0).setShow(!list.get(0).isShow());
                } else {
                    if (list.get(position).isShow()) {
                        list.get(position).setShow(false);
                    } else {
                        for (History history : list) {
                            history.setShow(list.indexOf(history) == position);
                        }
                    }
                }
                quickHistoryAdapter.notifyDataSetChanged();
            }
        });
        quickHistoryAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (normalBuilder == null) {
                    normalBuilder = new NormalDialog.Builder(MainActivity.this);
                }
                normalBuilder.setContent(ResUtil.getString(R.string.delete_tip));
                normalBuilder.setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (gson == null) {
                            gson = new Gson();
                        }
                        adapter.getData().remove(position);
                        MMKV.defaultMMKV().encode(Const.HISTORY_KEY, gson.toJson(adapter.getData()));
                        quickHistoryAdapter.notifyItemRemoved(position);
                        allHistory.remove(position);
                    }
                });
                normalBuilder.setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                normalBuilder.create().show();
                return false;
            }
        });
        quickHistoryAdapter.setEmptyView(R.layout.empty_item);
        View footerView = getLayoutInflater().inflate(R.layout.footer_item_clear_all, rvHistory, false);
        quickHistoryAdapter.addFooterView(footerView);
        footerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (normalBuilder == null) {
                    normalBuilder = new NormalDialog.Builder(MainActivity.this);
                }
                normalBuilder.setContent(ResUtil.getString(R.string.clear_all_tip));
                normalBuilder.setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MMKV.defaultMMKV().remove(Const.HISTORY_KEY);
                        allHistory.clear();
                        quickHistoryAdapter.setList(allHistory);
                    }
                });
                normalBuilder.setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                normalBuilder.create().show();
            }
        });

    }

    private void getCoinResult() {
        coinLayout.setVisibility(View.VISIBLE);
        Random random = new Random();

        boolean bool1 = random.nextBoolean();
        boolean bool2 = random.nextBoolean();
        boolean bool3 = random.nextBoolean();
        coin1.setText(bool1 ? R.string.front : R.string.reverse);
        coin2.setText(bool2 ? R.string.front : R.string.reverse);
        coin3.setText(bool3 ? R.string.front : R.string.reverse);
        if (clickCount == 0) {
            result1[0] = bool1 ? 1 : 0;
            result1[1] = bool2 ? 1 : 0;
            result1[2] = bool3 ? 1 : 0;
        } else if (clickCount == 1) {
            result2[0] = bool1 ? 1 : 0;
            result2[1] = bool2 ? 1 : 0;
            result2[2] = bool3 ? 1 : 0;
            //遍历Map
            Set<Map.Entry<int[], Integer>> entries = Const.eightDiagramsMap.entrySet();
            int numberOne = 0, numberTwo = 0;
            for (Map.Entry<int[], Integer> entry : entries) {
                if (Arrays.equals(entry.getKey(), result1)) {
                    numberOne = entry.getValue();
                }
                if (Arrays.equals(entry.getKey(), result2)) {
                    numberTwo = entry.getValue();
                }
            }
            int resultNumber = numberOne * 10 + numberTwo;

            for (Gua gua : dataList) {
                if (resultNumber == gua.getIndexGua()) {
                    nowGua = gua;
                    break;
                }
            }
            if (nowGua != null) {
                SpannableString text = new SpannableString(getResources().getString(R.string.result) + "\n" + " 第" + StringUtil.numberToChinese(nowGua.getId()) + "卦:" + nowGua.getName() + "-- \n" + nowGua.getDescrip());
                text.setSpan(new ForegroundColorSpan(Color.RED), text.toString().indexOf("卦:") + 2, text.toString().indexOf("--"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.dp_48), true), text.toString().indexOf("卦:") + 2, text.toString().indexOf("--"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvResult.setVisibility(View.VISIBLE);
                tvResult.setText(text);
                llGua.setVisibility(View.VISIBLE);
                gua1.setBackgroundResource(result1[0] == 1 ? R.color.black : R.drawable.yin);
                gua2.setBackgroundResource(result1[1] == 1 ? R.color.black : R.drawable.yin);
                gua3.setBackgroundResource(result1[2] == 1 ? R.color.black : R.drawable.yin);
                gua4.setBackgroundResource(result2[0] == 1 ? R.color.black : R.drawable.yin);
                gua5.setBackgroundResource(result2[1] == 1 ? R.color.black : R.drawable.yin);
                gua6.setBackgroundResource(result2[2] == 1 ? R.color.black : R.drawable.yin);
                History nowHistory = new History(System.currentTimeMillis(), nowGua);
                allHistory.add(nowHistory);
                allHistory.sort(new Comparator<History>() {
                    @Override
                    public int compare(History item1, History item2) {
                        return Long.compare(item2.getTime(), item1.getTime());
                    }
                });

                quickHistoryAdapter.setList(allHistory);
                mmkv.encode(Const.HISTORY_KEY, gson.toJson(allHistory));
            }
            tvStart.setText(R.string.try_gua_again);
        }
    }

    /**
     * 读取 JSON 数据的方法
     */
    private ArrayList<Gua> readJsonFromAssets() {
        try {
            // 打开 assets 文件夹中的 JSON 文件
            InputStream inputStream = getAssets().open("sixty_four_data.json");

            // 使用 InputStreamReader 读取 JSON 文件
            InputStreamReader reader = new InputStreamReader(inputStream);

            // 使用 Gson 解析 JSON 数据
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<Gua>>() {
            }.getType();

            // 返回解析得到的数据
            return gson.fromJson(reader, type);
        } catch (IOException e) {
            Log.e(TAG, "readJsonFromAssets e=" + e);
        }

        return null;
    }

    @Override
    public void onBackPressed() {
        if (rvAll != null && rvAll.getVisibility() == View.VISIBLE) {
            rvAll.setVisibility(View.GONE);
            tvSeeAll.setText(R.string.see_all);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadingDialog != null) {
            loadingDialog.hideLoading();
            loadingDialog = null;
        }
        if (historyDialog != null) {
            historyDialog.hide();
            historyDialog = null;
        }
    }
}